<script setup lang="ts">
import { TextValue, TSqlInfo } from '@/models/reactiveComponent';
import { computed, inject, ref } from 'vue'
import * as injectKeys from "@/services/injectKeys";
import { createSqlQueryMappingRunner } from '@/core/jsCodeRunner';
import { useElementSize, watchOnce } from '@vueuse/core';
import { isSqlInfo } from '@/models/utils';
import { TForeachMapping, TForeachRow } from '@/models/types';

const utilsServices = inject(injectKeys.utilsKey)!



const props = defineProps<{ model: TextValue }>()
const model = props.model



const content = computed(() => {
    const ctx = model.contexts.map(ct => {

        if (typeof ct === 'string') {
            return ct
        }

        if (isSqlInfo(ct)) {
            const sqlInfo = ct as TSqlInfo
            const sqlQuery = utilsServices.createSqlQuery(model.id, sqlInfo.sql)
            const mapRunner = createSqlQueryMappingRunner(sqlInfo.jsMap, sqlInfo.type)

            const data = sqlQuery.query()

            if (data.rows.length === 0) {
                return null
            }

            const res = mapRunner.map(data)
            let resStr = JSON.stringify(res)

            if (typeof res === 'string') {
                resStr = resStr.slice(1, -1)
            }

            return resStr
        }

        const sqlInfo = ct as TForeachMapping
        const foreachRowData = inject('foreachRow')! as TForeachRow
        return foreachRowData[sqlInfo.field]

    })
    return ctx.join('')
})

const boxRef = ref(null as unknown as HTMLDivElement)
const tableBoxHeight = ref('initial')

const { height } = useElementSize(boxRef)


watchOnce(height, height => {
    tableBoxHeight.value = height + 'px'
})

</script>

<template>
    <p ref="boxRef" class="textValue-box" v-html="content"></p>
</template>

<style scoped>
.textValue-box {
    display: inline-block;
    /* height: v-bind(tableBoxHeight); */
    white-space: pre-wrap;
    margin: 0;
    box-sizing: initial;
}
</style>